<template>
  <basic-container>
    <el-tabs v-model="activeName"
             @tab-click="handleClick">
      <el-tab-pane label="管理"
                   name="first">
        <avue-crud :option="option"
                   :data="data"
                   ref="formRef"
                   v-model="form"
                   @selection-change="selectionChange"
                   :table-loading="loading"
                   :permission="permission"
                   @row-del="rowDelList"
                   :page="page"
                   @refresh-change="refreshChange"
                   @search-change="searchChange"
                   @search-reset="searchReset"
                   @current-change="currentChange"
                   @size-change="sizeChange"
                   @on-load="onLoad">
          <template slot-scope="{row}"
                    slot="brandLogoUrl">
            <img v-if="row.brandLogoUrl" :src="row.brandLogoUrl"
                 style="width:50px;height:50px;" />
          </template>
          <template slot="menuLeft">
            <el-button type="primary"
                       size="mini"
                       @click="beforeOPen" v-has="'/mall-cloud-base/brand/addItem'">新建品牌</el-button>
            <!--<el-button type="primary" @click="delAll" size="mini">批量删除</el-button>-->
          </template>
          <template slot-scope="scope"
                    slot="menu">
            <el-button icon="el-icon-edit"
                       size="small"
                       type="text"
                       @click="editShow(scope.row)" v-has="'/mall-cloud-base/brand/editItem'">编辑</el-button>
          </template>
        </avue-crud>
        <!-- 新建按钮弹框 -->
        <el-dialog title="新建品牌"
                   :visible.sync="dialogVisible"
                   @before-close="closeDialog"
                   width="40%"
                   >
          <el-form :model="addForm"
                   :rules="rules"
                   ref="addForm"
                   label-width="110px"
                   class="demo-ruleForm">
            <el-form-item label="品牌名称"
                          prop="brandName">
              <el-input v-model="addForm.brandName"
                        placeholder="请输入品牌名称"
                        size="mini"></el-input>
            </el-form-item>
            <el-form-item label="首字母(大写)">
              <el-input v-model="addForm.firstWord"
                        placeholder="请输入首字母"
                        size="mini"></el-input>
            </el-form-item>
<!--            <el-form-item label="类别"-->
<!--                          prop="brandCategoryName">-->
<!--              <el-input v-model="addForm.brandCategoryName"-->
<!--                        placeholder="请输入类别"-->
<!--                        size="mini"></el-input>-->
<!--            </el-form-item>-->
            <el-form-item label="品牌图片">
              <div>
                <el-col style="width: calc(100% - 160px);">
					<div @click="$refs.selFile.open()">
						<el-form-item>
						  <el-input v-model="addForm.brandLogoUrl"
						            placeholder="请选择品牌图片,图片比例：1：1"
													  readonly
						            size="mini"></el-input>
						</el-form-item>
					</div>
                </el-col>
                <el-col style="width: 40px;height: 40px;overflow: hidden;margin-left: 15px;background: #f5f6f7;text-align: center;">
                  <div class="demo-image__preview">
                    <el-image :src="addForm.brandLogoUrl"
                              width="40"
                              height="40"
                              :preview-src-list="srcList">
                      <div slot="error" class="image-slot">
                        <i class="el-icon-picture-outline" style="font-size: 20px;"></i>
                      </div>
                    </el-image>
                  </div>
                </el-col>
                <el-col style="width: 90px;margin-left: 15px;">
                  <el-form-item >
                    <el-button size="mini"
                               icon="el-icon-search"
                               type="primary"
                               @click="$refs.selFile.open()">预览</el-button>
                    <selFile ref="selFile"
                             @callback="selFileCallBack"
                             albumCode="pic_root"
                             dialogTitle="选择图片"
                             selectType="radio"
                             selMaxWidth="300px"
                             selMaxHeight="300px"></selFile>
                  </el-form-item>
                </el-col>
              </div>
            </el-form-item>
            <el-form-item label="排序"
                          prop="brandSequence">
              <el-input type="number"
                        size="mini"
                        v-model="addForm.brandSequence"
                        placeholder="请输入排序号(数字)"></el-input>
            </el-form-item>
          </el-form>
          <span slot="footer"
                class="dialog-footer">
            <el-button type="primary"
                       size="mini"
                       @click="addrecurseData" :loading="aloadBtn">确 定</el-button>
            <el-button size="mini"
                       @click="closeDialog('addForm')">取 消</el-button>
          </span>
        </el-dialog>
        <!-- 编辑弹窗按钮 -->
        <el-dialog title="编辑"
                   :visible.sync="editVisible"
                   :before-close="editCloseDialog"
                   width="40%"
                   >
          <el-form :model="editForm"
                   :rules="editFormrules"
                   ref="editFormRef"
                   label-width="110px"
                   class="demo-ruleForm">
            <el-form-item label="品牌名称"
                          prop="brandName">
              <el-input size="mini" v-model="editForm.brandName"></el-input>
            </el-form-item>
            <el-form-item label="首字母(大写)" prop="firstWord">
              <el-input size="mini" v-model="editForm.firstWord"
                        placeholder="请输入大写首字母"></el-input>
            </el-form-item>
<!--            <el-form-item label="类别" prop="brandCategoryName">-->
<!--              <el-input size="mini" v-model="editForm.brandCategoryName"-->
<!--                        placeholder="请输入类别"></el-input>-->
<!--            </el-form-item>-->
            <el-form-item label="品牌图片" >
              <div>
                <el-col style="width: calc(100% - 160px);">
					<div @click="$refs.selFile.open()">
					  <el-form-item>
						<el-input size="mini"  v-model="editForm.brandLogoUrl"
								  placeholder="请选择品牌图片" readonly></el-input>
					  </el-form-item>
					</div>
                </el-col>
                <el-col style="width: 40px;height: 40px;overflow: hidden;margin-left: 15px;">
                  <div class="demo-image__preview">
                    <el-image :src="editForm.brandLogoUrl"
                              width="40"
                              height="40"
                              :preview-src-list="srcList">
                      <div slot="error" class="image-slot">
                        <i class="el-icon-picture-outline"></i>
                      </div>
                    </el-image>
                  </div>
                </el-col>
                <el-col style="width: 90px;margin-left: 15px;">
                  <el-form-item >
                    <el-button icon="el-icon-search"
                               type="primary"
                               size="medium"
                               @click="$refs.selFile.open()">预览</el-button>
                    <selFile ref="selFile"
                             @callback="selFileCallBack"
                             albumCode="pic_root"
                             dialogTitle="选择图片"
                             selectType="radio"
                             selMaxWidth="300px"
                             selMaxHeight="300px"></selFile>
                  </el-form-item>
                </el-col>
              </div>
            </el-form-item>
            <el-form-item label="排序"
                          prop="brandSequence">
              <el-input type="number" v-model="editForm.brandSequence"></el-input>
            </el-form-item>
          </el-form>
          <span slot="footer"
                class="dialog-footer">
            <el-button type="primary"
                       @click="editRecurseData" :loading="eloadBtn" size="mini" v-has="'/mall-cloud-base/brand/editItem'">确 定</el-button>
            <el-button @click="editCloseDialog('editFormRef')" size="mini">取 消</el-button>
          </span>
        </el-dialog>
      </el-tab-pane>
      <!-- 申请列表 -->
      <el-tab-pane label="申请列表"
                   name="third">
        <avue-crud :option="option1"
                   :data="dataList"
                   ref="crud"
                   v-model="form"
                   :table-loading="loading"
                   @selection-change="selectionChange2"
                   :permission="permission"
                   @row-del="rowDelList"
                   @row-update="rowUpdateList"
                   @row-save="rowSaveList"
                   :page="page1"
                   @refresh-change="refreshChangeList"
                   @search-change="searchChangeList"
                   @search-reset="searchResetList"
                   @current-change="currentChangeList"
                   @size-change="sizeChangeList"
                   @on-load="onLoadList">
          <template slot-scope="{row}"
                    slot="brandLogoUrl">
            <img v-if="row.brandLogoUrl" :src="row.brandLogoUrl"
                 style="width:50px;height:50px;" />
          </template>
          <template slot="menuLeft">
            <!--<el-button type="primary" @click="delAll2" size="mini">批量删除</el-button>-->
          </template>
          <template slot-scope="{row}"
                    slot="menu">
            <el-button type="text"
                       size="small"
                       @click.stop="approve(row.id,1)">通过</el-button>
            <el-button type="text"
                       size="small"
                       @click.stop="approve(row.id,-1)">拒绝</el-button>
          </template>
        </avue-crud>
      </el-tab-pane>
    </el-tabs>
  </basic-container>
</template>

<script>
import selFile from "@/components/file/selFile";
import uploadPic from "@/components/file/uploadPic";
import {isWord,isPicture} from '@/util/rej'
import {
  getList,
  remove,
  update,
  add,
  deletes,
  approveBrand
} from "@/api/base/goods/brand";
import {
  mapGetters
} from "vuex";
import {
  isInteger,
  testSort,
  testGoodsName
} from '@/util/util'

var Dict = JSON.parse(localStorage.getItem("mall-dictionary")).content;
export default {
  data () {
    return {
      aloadBtn:false,
      eloadBtn:false,
      idList: [],
      idList2: [],
      // 新建按钮内容
      addForm: {
        brandName:'',
        firstWord:'',
        // brandCategoryName:'',
        brandLogoUrl:'',
        brandSequence:'',
      },
      rules: {
        brandName: [{
          required: true,
          message: "品牌名称不能为空",
        },
        {
          min: 2,
          max: 10,
          message: "长度在 2 到 10个字符",
        },{
            validator:testGoodsName,
            trigger: 'blur'
          },
        ],
        brandSequence: [{
          required: true,
          message: "请输入排序(数字)",
          trigger:'change'
        },{
          validator: testSort,
          trigger: 'blur'
        }],
        firstWord: [
        {
          max: 1,
          message: "长度必须为1",
        },
          {
          validator: isWord,
          }
        ],brandLogoUrl: [{
          required: true,
          message: '品牌图片不能为空',
          trigger: 'blur'
        },
          {
          validator: isPicture,
        }
        ],
        // brandCategoryName: [{
        //   required: true,
        //   message: '请输入类别',
        //   trigger: 'blur'
        // },
        //   {
        //     min: 1,
        //     max: 6,
        //     message: '长度在 1 到 6 个字符',
        //     trigger: 'blur'
        //   }
        // ]
      },
      // 编辑按钮内容
      editForm: {
        brandName:'',
        firstWord:'',
        // brandCategoryName:'',
        brandLogoUrl:'',
        brandSequence:'',
      },
      editFormrules:{
      brandName: [
        {
        required: true,
        message: "品牌名称不能为空",
      },
        {
          validator:testGoodsName,
          trigger: 'blur'
        },
        {
          min: 2,
          max: 10,
          message: "长度在 2 到 10个字符",
        }
      ],
     brandSequence: [
      {
        required: true,
        message: "请输入排序(数字)",
      },
      {
        validator: testSort,
      }],
      firstWord: [
        {
          max: 1,
          message: "长度必须为1",
        },
        {
          validator: isWord,
        }
      ],
        brandLogoUrl: [{
        required: true,
        message: '品牌图片不能为空',
        trigger: 'blur'
      },
        {
          validator: isPicture,
        }
      ],
      //         brandCategoryName: [{
      //   required: true,
      //   message: '请输入类别',
      //   trigger: 'blur'
      // },
      //   {
      //     min: 1,
      //     max: 6,
      //     message: '长度在 1 到 6 个字符',
      //     trigger: 'blur'
      //   }
      // ]
    },
      dialogVisible: false,
      data: [],
      editVisible: false,
      form: {},
      query: {},
      loading: true,
      rolesTree: [],
      rolesKeys: [],
      // 申请列表数据
      dataList: [],
      box: false,
      activeName: "first",
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      page1: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      srcList: [],
      option: {
        size: "mini",
        excelBtn: false,
        tip: false,
        border: true,
        index: false,
        addBtn: false,
        editBtn: false,
        refreshBtn: true,
        dialogType: "dialog",
        align: "center",
        viewBtn: false,
        rowKey: "id",
        height: "auto",
        // calcHeight: 380,
        menuWidth: 150,
        searchMenuSpan:6,
        column: [{
          label: "排序",
          prop: "brandSequence",
          type: 'number',
          width:90
        },
        {
          label: "首字母",
          prop: "firstWord",
          width:90
        },
        {
          label: "品牌名称",
          prop: "brandName",
          search: true
        },
        {
          label: "品牌图片",
          prop: "brandLogoUrl",
          slot: true,
          width:150
        },
        // {
        //   label: "类别",
        //   prop: "brandCategoryName",
        //   search: true,
        //   width:150
        // }
        ]
      },
      option1: {
        size: "mini",
        excelBtn: false,
        tip: false,
        border: true,
        index: false,
        selection: false,
        addBtn: false,
        editBtn: false,
        delBtn: false,
        columnBtn: false,
        refreshBtn: false,
        searchBtn: false,
        viewBtn: false,
        align: "center",
        rowKey: "id",
        // calcHeight: 380,
        menuWidth: 150,
        column: [{
          label: "品牌名称",
          prop: "brandName",
          search: true,
          rules: [{
            required: true,
            trigger: "blur"
          },{
            validator:testGoodsName,
            trigger: 'blur'
          },]
        },
        {
          label: "店铺名称",
          prop: "storeName"
        },
        {
          label: "品牌图片标识",
          prop: "brandLogoUrl",
          slot: true,
          width:150,
          rules: [{
            required: true,
            message: "请输入品牌名称",
            trigger: "blur"
          }]
        },
        {
          label: "品牌描述",
          prop: "brandRemark",
          rules: [{
            required: true,
            message: "请输入评论内容",
            trigger: "blur"
          }]
        },
        {
          label: "审核状态",
          prop: "brandAudit",
          width:150,
          dicData: Dict.STORE_BRAND_STATUS
        }
        ]
      }
    };
  },
  computed: {
    ...mapGetters(["permission", "userInfo"]),
    permissionList () {
      return {
        delBtn: this.vaildData(
          this.permission["/mall-cloud-base/brand/delete"],
          false
        ),
      };
    }
  },
  components: {
    selFile,
    uploadPic
  },
  watch:{
    editVisible(val){
      if(!val){
        this.$nextTick(()=>{
          this.$refs["editFormRef"].resetFields();
        })
      }
    },
    dialogVisible(val){
      if(!val){
        this.$nextTick(()=>{
          this.$refs["addForm"].resetFields();
        })
      }
    },

  },
  methods: {
    // 选择图片
    selFileCallBack (obj) {
      this.addForm.brandLogoUrl = obj[0];
      this.editForm.brandLogoUrl = obj[0];
    },
    // 弹窗新增页面
    addrecurseData () {
      console.log(this.addForm);
      let re = /[A-Z]/
      if(this.addForm.firstWord){
        if(this.addForm.firstWord.length>1){
          this.$message.error('首字母长度为1');
          return;
        }
        if(!re.test(this.addForm.firstWord)  ){
          this.$message.error('首字母必须为大写字母');
          return;
        }
      }
      //如果图片不为空，校验一下，否则不校验
      if(this.addForm.brandLogoUrl){
        let isPicture = this.isPicture(this.addForm.brandLogoUrl);
        if(!isPicture){
          this.$message.error('请填写正确的图片格式');
        }
      }
      this.$refs['addForm'].validate((valid) => {
        if (valid) {
          this.aloadBtn=true
          add(this.addForm).then((res) => {
            if(res.status==200){
              this.aloadBtn=false
              this.onLoad(this.page);
              this.$message({
                type: "success",
                message: "添加品牌成功!"
              });
            }
          });
          this.dialogVisible = false;
        } else {
          this.$message({
            type: "error",
            message: "请输入品牌正确信息!"
          });
          return false;
        }
      });
    },
    // 新增关闭按钮
    closeDialog () {
      this.$nextTick(()=>{
        this.$refs["addForm"].resetFields();
      })
      this.dialogVisible = false;
      this.aloadBtn=false
    },
    beforeOPen () {
      this.addForm = {
        brandName:'',
        firstWord:'',
        // brandCategoryName:'',
        brandLogoUrl:'',
        brandSequence:'',
      };
      this.dialogVisible = true;

    },
    // 点击编辑按钮，调用根据id查询信息按钮，获取信息显示在页面上
    editShow (row) {
      this.editVisible = true;
      this.editForm = row
    },
    // 编辑确定按钮
    editRecurseData () {
      let re = /[A-Z]/
      if(this.addForm.firstWord){
        if(this.addForm.firstWord.length>1){
          this.$message.error('首字母长度为1');
          return;
        }

        if(!re.test(this.addForm.firstWord)  ){
          this.$message.error('首字母必须为大写字母');
          return;
        }
      }

      if((this.editForm.brandSequence) && this.editForm.brandSequence.toString().length>9){
        this.$message.error('商品排序输入长度不能超过9位');
        return;
      }
       if(this.editForm.brandSequence === "" || this.editForm.brandSequence==undefined || this.editForm.brandSequence==null){
         console.log(this.editForm.brandSequence)
           this.$message.error("商品排序输入不能为空");
           return;
       }
       if(this.editForm.brandName === "" || this.editForm.brandName==null || this.editForm.brandName==undefined){
           this.$message.error("商品品牌输入不能为空");
           return;
       }
      if(this.editForm.brandLogoUrl){
        let isPicture = this.isPicture(this.editForm.brandLogoUrl);
        if(!isPicture){
          this.$message.error('请填写正确的图片格式');
        }
      }
      this.$refs['editFormRef'].validate((valid) => {
        if (valid) {
          this.eloadBtn=true
          update(this.editForm).then(res => {
            if (res.data.code == 200) {
              this.eloadBtn=false
              this.loading = false;
              this.$message({
                type: "success",
                message: "操作成功!"
              });
              this.onLoad(this.page);
            } else {
              return false;
            }
          });
          this.editVisible = false;
        } else {
          return false;
        }
      });
    },
    // 编辑关闭按钮
    editCloseDialog () {
      this.editVisible = false;
      this.$nextTick(()=>{
        this.$refs["editFormRef"].resetFields();
      })
      this.eloadBtn=false

    },
    // 点击tab页跳转
    handleClick () { },
    rowDel (row) {
      this.$confirm("确定将选择数据删除?", {
        cancelButtonText: "取消",
        confirmButtonText: "确定",
        type: "warning"
      })
        .then(() => {
          return remove(row.id);
        })
        .then(res => {
          if (res.data.success) {
            this.page.currentPage = 1;
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          }
          else {
            this.$message.error(res.data.message);
          }

        });
    },
    searchReset () {
      this.idList = []
      this.$refs.formRef.toggleSelection();
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange (params,done) {
      this.idList = []
      this.$refs.formRef.toggleSelection();
      this.page.currentPage = 1
      this.query = params;
      this.onLoad(this.page, params,done);
    },
    currentChange (currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange (pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange () {
      this.onLoad(this.page);
    },
    onLoad (page, params = {},done) {
      params.brandAudit = 1;
      this.loading = true;
      getList(
        page.currentPage,
        page.pageSize,
        Object.assign(params, this.query)
      ).then(res => {
        if(done){
          done();
        }
        this.loading = false;
        const data = res.data;
        this.page.total = data.count;
        this.data = data.data;
      });
    },
    selectionChange (row) {
      this.idList2 = this.handleData(row)
    },
    delAll () {
      if (this.idList.length == 0) {
        this.$message.error("请先选择要删除的对象!")
        return;
      }
      deletes(this.idList).then(res => {
        if (res.data.code == 200) {
          this.refreshChange();
          this.$message({
            type: "success",
            message: "删除成功!"
          });
        } else {
          this.$message.error(res.data.message);
        }
      })
    },
    // 申请列表
    //监控多选点击事件
    selectionChange2 (row) {
      this.idList = this.handleData(row)
    },
    handleData (data) {
      let arr = data.map(item => {
        return item.id.toString()
      })
      return arr
    },
    delAll2 () {
      if (this.idList2.length == 0) {
        this.$message.info("请先选择要删除的对象!")
        return;
      }
      deletes(this.idList2).then(res => {
        if (res.data.code == 200) {
          this.refreshChange();
          this.$message({
            type: "success",
            message: "删除成功!"
          });
        } else {
          this.$message.error(res.data.message);
        }
      })
    },

    rowSaveList (row, loading, done) {
      row.position = row.positionIds;
      row.deptName = row.$deptId;
      row.repassword = row.password;
      add(row).then(
        () => {
          loading();
          this.onLoadList(this.page1);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        },
        error => {
          done();
          console.log(error);
        }
      );
    },
    rowUpdateList (row, index, loading, done) {
      row.position = row.positionIds;
      update(row).then(
        () => {
          loading();
          this.onLoadList(this.page1);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        },
        error => {
          done();
          console.log(error);
        }
      );
    },
    rowDelList (row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(row.id);
        })
        .then(res => {
          if (res.data.success) {
            this.page.currentPage = 1
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          }
          else {
            this.$message.error(res.data.message);
          }

        });
    },
    searchResetList () {
      this.idList2 = []
      this.$refs.crud.toggleSelection();
      this.query = {};
      this.onLoadList(this.page1);
    },
    searchChangeList (params,done) {
      this.idList = []
      this.$refs.crud.toggleSelection();
      this.page.currentPage = 1
      this.query = params;
      this.onLoadList(this.page1, params,done);
    },
    // 分页
    currentChangeList (currentPage) {
      this.page1.currentPage = currentPage;
      this.onLoadList(this.page1);
    },
    sizeChangeList (pageSize) {
      this.page1.pageSize = pageSize;
      this.onLoadList(this.page1);
    },
    refreshChangeList () {
      this.idList = []
      this.$refs.crud.toggleSelection();
      this.onLoadList(this.page1);
    },
    onLoadList (page, params = {},done) {
      params.brandAudit = 0;
      this.loading = true;
      getList(
        page.currentPage,
        page.pageSize,
        Object.assign(params, this.query)
      ).then(res => {
        if(done){
          done();
        }
        this.loading = false;
        const dataList = res.data;
        console.log(dataList);
        this.page1.total = dataList.count;
        this.dataList = dataList.data;
        if (res.status == 200) {
          this.dataList = [];
          this.dataList = dataList.data;
        }
      });
    },
    approve (id, status) {
      approveBrand(id, status).then(() => {
        this.page1.currentPage=1
        this.page.currentPage=1
        this.onLoadList(this.page1);
        this.onLoad(this.page);
      });
    },
    isPicture(value){
      let idPicture = false;
      if (value.indexOf('.jpg') == -1 && value.indexOf('.png') == -1) {
        return idPicture;
      } else {
        return idPicture = true
      }
    }
  }
};
</script>

<style>
</style>
